﻿Imports DotNetNuke
Imports DotNetNuke.Common
Imports DotNetNuke.Security
Imports DotNetNuke.Entities.Profile
Imports DotNetNuke.Entities.Users
Imports DotNetNuke.Entities.Users.UserProfile
Imports System.Web.UI
Imports Telerik.Web.UI
Imports DotNetNuke.Security.Membership
Imports DotNetNuke.Services.Mail

Namespace dnnWerk.Modules.Users

    Partial Class uc_Profile
        Inherits UserModuleBase

        Private blnPageNeedsToPostback As Boolean = False

#Region "Event Handlers"

        Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init

            DotNetNuke.Framework.AJAX.RegisterScriptManager()

            ProcessFormTemplate(plhProfile, Template_UserProfile(CurrentLocale), User, blnPageNeedsToPostback)

            Dim btnUpdate As Button = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_UpdateButton), Button)
            If Not btnUpdate Is Nothing Then

                AddHandler btnUpdate.Click, AddressOf btnUpdate_Click

                If blnPageNeedsToPostback Then
                    DotNetNuke.Framework.AJAX.RegisterPostBackControl(btnUpdate)
                End If

            End If

            Dim btnDelete As Button = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_DeleteButton), Button)
            If Not btnDelete Is Nothing Then

                AddHandler btnDelete.Click, AddressOf btnDelete_Click

            End If

            Me.ctlDecorate.Visible = Me.DecorateForm
            Me.ctlDecorate.Enabled = Me.DecorateForm

        End Sub

        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        End Sub

        Protected Sub btnUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            UpdateProfile()
        End Sub

        Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            DeleteAccount()
        End Sub

        Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
            'If Page.IsPostBack Then
            '    ProcessFormTemplate(plhProfile, Template_UpdateProfile(CurrentLocale), User, blnPageNeedsToPostback)
            'End If
        End Sub


#End Region

#Region "Private Methods"

        Private Sub Update()

            pnlSuccess.Visible = False
            pnlError.Visible = False

            Dim strMessage As String = ""

            Dim blnUpdateUsername As Boolean = False
            Dim blnUpdateFirstname As Boolean = False
            Dim blnUpdateLastname As Boolean = False
            Dim blnUpdateDisplayname As Boolean = False
            Dim blnUpdatePassword As Boolean = False
            Dim blnUpdateEmail As Boolean = False            

            Dim txtUsername As RadTextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Username), RadTextBox)
            blnUpdateUsername = (Not txtUsername Is Nothing)

            If blnUpdateUsername AndAlso IsRegisterMode() Then
                If Not IsValidUserAttribute(Constants.User_Username, plhProfile) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Username, plhProfile)
                End If
            End If

            Dim txtEmail As RadTextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Email), RadTextBox)
            blnUpdateEmail = (Not txtEmail Is Nothing)

            If blnUpdateEmail Then
                If Not IsValidUserAttribute(Constants.User_Email, plhProfile) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Email, plhProfile)
                End If
            End If

            Dim txtPassword As RadTextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Password1), RadTextBox)
            Dim txtPassword2 As RadTextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Password2), RadTextBox)
            blnUpdatePassword = (Not txtPassword Is Nothing AndAlso Not txtPassword2 Is Nothing)

            If blnUpdatePassword Then
                If txtPassword.Text = "" AndAlso txtPassword2.Text = "" Then
                    blnUpdatePassword = False
                End If
            End If

            If blnUpdatePassword Then
                If Not IsValidUserAttribute(Constants.User_Password1, plhProfile) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Password1, plhProfile)
                End If
                If Not IsValidUserAttribute(Constants.User_Password2, plhProfile) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Password2, plhProfile)
                End If
            End If

            Dim txtFirstName As RadTextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Firstname), RadTextBox)
            blnUpdateFirstname = (Not txtFirstName Is Nothing)

            If blnUpdateFirstname Then
                If Not IsValidUserAttribute(Constants.User_Firstname, plhProfile) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Firstname, plhProfile)
                End If
            End If

            Dim txtLastName As RadTextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Lastname), RadTextBox)
            blnUpdateLastname = (Not txtLastName Is Nothing)

            If blnUpdateLastname Then
                If Not IsValidUserAttribute(Constants.User_Lastname, plhProfile) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Lastname, plhProfile)
                End If
            End If

            Dim txtDisplayName As RadTextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Displayname), RadTextBox)
            blnUpdateDisplayname = (Not txtDisplayName Is Nothing)

            If blnUpdateDisplayname Then
                If Not IsValidUserAttribute(Constants.User_Displayname, plhProfile) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Displayname, plhProfile)
                End If
            End If

            For Each itemProp As String In GetPropertiesFromTempate(Template_UserProfile(CurrentLocale))
                Try
                    Dim prop As ProfilePropertyDefinition = ProfileController.GetPropertyDefinitionByName(PortalId, itemProp.Substring(2)) 'itemprop comes in the form U:Propertyname or P:Propertyname
                    If Not prop Is Nothing Then
                        If Not IsValidProperty(UserInfo, prop, plhProfile) Then
                            strMessage += "Error"
                            AddErrorIndicator(prop.PropertyDefinitionId.ToString, plhProfile)
                        End If
                    End If
                Catch
                End Try
            Next

            If strMessage.Length > 0 Then
                Me.pnlError.Visible = True
                Me.lblError.Text = "<ul><li>Sie müssen alle erforderlichen Felder ausfüllen!</li></ul>"
                Exit Sub
            End If

            'all good so far, let's update the profile

            Dim oUser As UserInfo = Nothing
            If IsRegisterMode() Then 'new registration

                oUser = New UserInfo

                If PortalSettings.UserRegistration = PortalRegistrationType.PublicRegistration Then
                    oUser.Membership.Approved = True
                Else
                    oUser.Membership.Approved = False
                End If

                oUser.AffiliateID = Null.NullInteger
                oUser.PortalID = PortalSettings.PortalId
                oUser.Username = ""
                oUser.DisplayName = ""
                oUser.Email = ""
                oUser.Membership.Password = ""

                'set username depending on setting
                Select Case UsernameMode
                    Case UsernameUpdateMode.Email
                        If blnUpdateEmail Then
                            oUser.Username = txtEmail.Text.Trim
                        End If
                    Case UsernameUpdateMode.FirstLetterLastname
                        If blnUpdateLastname AndAlso blnUpdateFirstname Then
                            oUser.Username = txtFirstName.Text.Trim.Substring(0, 1) & "." & txtLastName.Text
                        End If
                    Case UsernameUpdateMode.FirstnameLastname
                        If blnUpdateLastname AndAlso blnUpdateFirstname Then
                            oUser.Username = txtFirstName.Text & "." & txtLastName.Text
                        End If
                    Case UsernameUpdateMode.Lastname
                        If blnUpdateLastname Then
                            oUser.Username = txtLastName.Text
                        End If
                    Case UsernameUpdateMode.UserSelect
                        If blnUpdateUsername Then
                            oUser.Username = txtUsername.Text
                        End If
                End Select

                'set displayname depending on setting
                Select Case DisplaynameMode
                    Case DisplaynameUpdateMode.Email
                        If blnUpdateEmail Then
                            oUser.DisplayName = txtEmail.Text.Trim
                        End If
                    Case DisplaynameUpdateMode.FirstLetterLastname
                        If blnUpdateLastname AndAlso blnUpdateFirstname Then
                            oUser.DisplayName = txtFirstName.Text.Trim.Substring(0, 1) & ". " & txtLastName.Text
                        End If
                    Case DisplaynameUpdateMode.FirstnameLastname
                        If blnUpdateLastname AndAlso blnUpdateFirstname Then
                            oUser.DisplayName = txtFirstName.Text & " " & txtLastName.Text
                        End If
                    Case DisplaynameUpdateMode.Lastname
                        If blnUpdateLastname Then
                            oUser.DisplayName = txtLastName.Text
                        End If
                    Case DisplaynameUpdateMode.UserSelect
                        If blnUpdateDisplayname Then
                            oUser.DisplayName = txtDisplayName.Text
                        End If
                End Select

            Else

                'profile update mode, get current user first
                oUser = User

            End If

            If blnUpdateEmail Then
                oUser.Email = txtEmail.Text
            End If

            'try updating password
            If blnUpdatePassword Then

                If txtPassword.Text = txtPassword2.Text Then
                    If UserController.ValidatePassword(txtPassword.Text) Then

                        UserController.ChangePassword(oUser, "", txtPassword.Text)

                    Else

                        Me.pnlError.Visible = True
                        Me.lblError.Text = "<ul><li>Das gewünschte Passwort entspricht nicht unseren Passwortrichtlinien!</li></ul>"
                        Exit Sub

                    End If
                Else

                    Me.pnlError.Visible = True
                    Me.lblError.Text = "<ul><li>Die Passwörter stimmen nicht überein!</li></ul>"
                    Exit Sub

                End If
            Else
                If IsRegisterMode() Then
                    oUser.Membership.Password = UserController.GeneratePassword(7)
                End If
            End If

            'try updating displayname

            If blnUpdateDisplayname AndAlso Not IsRegisterMode() Then
                oUser.DisplayName = txtDisplayName.Text
            End If

            'try updating firstname
            If blnUpdateFirstname Then
                oUser.FirstName = txtFirstName.Text
            End If

            'try updating lastname
            If blnUpdateLastname Then
                oUser.LastName = txtLastName.Text
            End If

            If IsRegisterMode() Then
                If oUser.Username = "" Or oUser.Email = "" Or oUser.DisplayName = "" Or oUser.Membership.Password = "" Then
                    'template must be setup up wrong
                    Me.pnlError.Visible = True
                    Me.lblError.Text = "<ul><li>Zur Zeit kann leider keine Registrierung vorgenommen werden. Bitte kontaktieren Sie den Webmaster dieser Seite.</li></ul>"
                End If
            End If

            Dim strBody As String = "<table border=""0""><tr><td colspan=""2"" style=""padding-top:10px;padding-bottom:10px;"">"

            If IsRegisterMode() Then
                strBody += "Ein neuer Benutzer hat sich registriert:</td></tr>"
            Else
                strBody += "Der Benutzer " & User.DisplayName & " hat seine Profildaten aktualisiert!</td></tr>"
            End If

            strBody += vbCrLf
            strBody += vbCrLf

            'set up profile
            If IsRegisterMode() Then
                oUser.Profile = New UserProfile
                oUser.Profile.InitialiseProfile(PortalSettings.PortalId, True)
            End If

            'loop trough dynamic profile attributes and set those
            For Each itemProp As String In GetPropertiesFromTempate(Template_UserProfile(CurrentLocale))
                Try
                    Dim prop As ProfilePropertyDefinition = ProfileController.GetPropertyDefinitionByName(PortalId, itemProp.Substring(2))
                    If Not prop Is Nothing Then

                        Dim ctl As Control = GetPropertyControl(prop, plhProfile)
                        If Not ctl Is Nothing Then
                            strBody += "<tr><td>"
                            If TypeOf (ctl) Is Telerik.Web.UI.RadComboBox Then
                                oUser.Profile.SetProfileProperty(prop.PropertyName, CType(ctl, Telerik.Web.UI.RadComboBox).Text.Trim)
                                strBody += LocalizeProperty(prop) & "</td><td>" & CType(ctl, Telerik.Web.UI.RadComboBox).Text.Trim
                            ElseIf TypeOf (ctl) Is Telerik.Web.UI.RadDateTimePicker Then
                                oUser.Profile.SetProfileProperty(prop.PropertyName, CType(ctl, Telerik.Web.UI.RadDateTimePicker).DbSelectedDate.ToString)
                                strBody += LocalizeProperty(prop) & "</td><td>" & CType(ctl, Telerik.Web.UI.RadDateTimePicker).DbSelectedDate.ToString
                            ElseIf TypeOf (ctl) Is Telerik.Web.UI.RadTimePicker Then
                                oUser.Profile.SetProfileProperty(prop.PropertyName, CType(ctl, Telerik.Web.UI.RadTimePicker).DbSelectedDate.ToString)
                                strBody += LocalizeProperty(prop) & "</td><td>" & CType(ctl, Telerik.Web.UI.RadTimePicker).DbSelectedDate.ToString
                            ElseIf TypeOf (ctl) Is CheckBox Then
                                oUser.Profile.SetProfileProperty(prop.PropertyName, CType(ctl, CheckBox).Checked.ToString)
                                strBody += LocalizeProperty(prop) & "</td><td>" & CType(ctl, CheckBox).Checked.ToString
                            ElseIf TypeOf (ctl) Is Telerik.Web.UI.RadTextBox Then
                                oUser.Profile.SetProfileProperty(prop.PropertyName, CType(ctl, Telerik.Web.UI.RadTextBox).Text.Trim)
                                strBody += LocalizeProperty(prop) & "</td><td>" & CType(ctl, Telerik.Web.UI.RadTextBox).Text.Trim
                            ElseIf TypeOf (ctl) Is Telerik.Web.UI.RadNumericTextBox Then
                                oUser.Profile.SetProfileProperty(prop.PropertyName, CType(ctl, Telerik.Web.UI.RadNumericTextBox).Value.ToString)
                                strBody += LocalizeProperty(prop) & "</td><td>" & CType(ctl, Telerik.Web.UI.RadNumericTextBox).Value.ToString
                            ElseIf TypeOf (ctl) Is Telerik.Web.UI.RadAsyncUpload Then

                                Dim objFile As UploadedFile = CType(ctl, Telerik.Web.UI.RadUpload).UploadedFiles(0)
                                If Not objFile Is Nothing Then
                                    Dim strFile As String = objFile.GetName
                                    Dim path As String = "Profile/" & prop.PropertyName & "/" & oUser.Username & "/" & strFile

                                    oUser.Profile.SetProfileProperty(prop.PropertyName, path)

                                    strBody += LocalizeProperty(prop) & "</td><td>" & strFile

                                End If

                            End If
                            strBody += "</td></tr>"
                        End If

                    End If
                Catch
                End Try
            Next

            strBody += "</table>"
            strBody += "<p><a href=""http://" & PortalSettings.PortalAlias.HTTPAlias & "/Admin/UserAccounts/tabid/42/ctl/Edit/mid/358/UserId/" & oUser.UserID.ToString & "/filter/alle/currentpage/1/Default.aspx"">Zum Benutzerkonto</a></p>"

            oUser.FirstName = oUser.Profile.FirstName
            oUser.LastName = oUser.Profile.LastName

            If blnUpdateFirstname = True Then
                oUser.Profile.FirstName = txtFirstName.Text
            Else
                If oUser.Profile.FirstName <> "" Then
                    oUser.FirstName = oUser.Profile.FirstName
                End If
            End If

            If blnUpdateLastname = True Then
                oUser.Profile.LastName = txtLastName.Text
            Else
                If oUser.Profile.LastName <> "" Then
                    oUser.LastName = oUser.Profile.LastName
                End If
            End If


            If IsRegisterMode() Then

                'see if we can create the account
                Dim createStatus As UserCreateStatus = UserController.CreateUser(oUser)
                If createStatus <> UserCreateStatus.Success Then

                    Select Case createStatus
                        Case UserCreateStatus.UsernameAlreadyExists
                            Select Case UsernameMode
                                Case UsernameUpdateMode.UserSelect
                                    strMessage = Localization.GetString("UsernameAlreadyExists", Me.SharedResourcefile)
                                Case UsernameUpdateMode.Email
                                    strMessage = Localization.GetString("DuplicateEmail", Me.SharedResourcefile)
                                Case UsernameUpdateMode.FirstnameLastname, UsernameUpdateMode.FirstLetterLastname, UsernameUpdateMode.Lastname
                                    strMessage = Localization.GetString("NameAlreadyExists", Me.SharedResourcefile)
                            End Select
                        Case Else
                            strMessage = Localization.GetString("createStatus", Me.SharedResourcefile)
                    End Select

                    If strMessage <> "" Then
                        strMessage = "<li>" & strMessage & "</li>"
                    Else
                        strMessage = "<li>" & createStatus.ToString & "</li>"
                    End If

                    Me.pnlError.Visible = True
                    Me.lblError.Text = "<ul>" & strMessage & "</ul>"

                    Exit Sub
                End If

                'update profile
                ProfileController.UpdateUserProfile(oUser)

                'notify admin   
                'Services.Mail.Mail.SendMail(oUser, MessageType.UserRegistrationAdmin, PortalSettings)
                'notify admin   
                If NotifyAddress <> "" Then
                    Try
                        Services.Mail.Mail.SendMail(PortalSettings.Email, NotifyAddress, "", String.Format(Localization.GetString("NotifySubject_UserRegistered", SharedResourcefile), PortalSettings.PortalName), strBody, "", "", "", "", "", "")
                    Catch
                    End Try
                End If

                Select Case PortalSettings.UserRegistration

                    Case PortalRegistrationType.PrivateRegistration

                        DotNetNuke.Services.Mail.Mail.SendMail(oUser, MessageType.UserRegistrationPrivate, PortalSettings)

                    Case PortalRegistrationType.VerifiedRegistration

                        DotNetNuke.Services.Mail.Mail.SendMail(oUser, MessageType.UserRegistrationVerified, PortalSettings)

                    Case Else

                        'logon user
                        Dim logonStatus As Membership.UserLoginStatus = UserLoginStatus.LOGIN_FAILURE
                        UserController.UserLogin(PortalId, oUser.Username, oUser.Membership.Password, "", PortalSettings.PortalName, Request.UserHostAddress, logonStatus, True)

                        'see if all worked
                        If logonStatus <> UserLoginStatus.LOGIN_SUCCESS Then

                            strMessage += logonStatus.ToString
                            Me.pnlError.Visible = True
                            Me.lblError.Text = strMessage
                            Exit Sub

                        End If

                End Select

                'add to role
                If AddToRoleOnSubmit <> Null.NullInteger Then
                    Try
                        Dim rc As New Security.Roles.RoleController
                        rc.AddUserRole(PortalId, oUser.UserID, AddToRoleOnSubmit, Null.NullDate)
                    Catch
                    End Try
                End If

                'remove to role
                If RemoveFromRoleOnSubmit <> Null.NullInteger Then
                    Try
                        Dim rc As New Security.Roles.RoleController
                        rc.DeleteUserRole(PortalId, oUser.UserID, RemoveFromRoleOnSubmit)
                    Catch
                    End Try
                End If

                lblSucess.Text = "<ul><li>" & String.Format(Localization.GetString("RegisterSuccess", SharedResourcefile), NavigateURL()) & "</li></ul>"

            Else

                'update profile
                UserController.UpdateUser(PortalId, oUser)

                'notify admin   
                If NotifyAddress <> "" Then
                    Try
                        Services.Mail.Mail.SendMail(PortalSettings.Email, NotifyAddress, "", String.Format(Localization.GetString("NotifySubject_ProfileUpdate", SharedResourcefile), PortalSettings.PortalName), strBody, "", "", "", "", "", "")
                    Catch
                    End Try
                End If

                lblSucess.Text = "<ul><li>" & Localization.GetString("ProfileUpdateSuccess.Text", SharedResourcefile) & "</li></ul>"

            End If

            Try
                oUser.Profile.SetProfileProperty("Email", oUser.Email)
            Catch
            End Try


            If RedirectAfterSubmit <> "" Then
                Response.Redirect(RedirectAfterSubmit, True)
            Else
                pnlSuccess.Visible = True
            End If

        End Sub

        Private Sub UpdateProfile()

            pnlSuccess.Visible = False
            pnlError.Visible = False

            Dim strMessage As String = ""
            Dim strUpdated As String = ""

            Dim blnUpdateUsername As Boolean = False
            Dim blnUpdateFirstname As Boolean = False
            Dim blnUpdateLastname As Boolean = False
            Dim blnUpdateDisplayname As Boolean = False
            Dim blnUpdatePassword As Boolean = False
            Dim blnUpdateEmail As Boolean = False

            Dim txtUsername As RadTextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Username), RadTextBox)
            blnUpdateUsername = (Not txtUsername Is Nothing)

            If blnUpdateUsername AndAlso IsRegisterMode() Then
                If Not IsValidUserAttribute(Constants.User_Username, plhProfile) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Username, plhProfile)
                Else
                    RemoveErrorIndicator(Constants.User_Username, plhProfile, True)
                End If
            End If

            Dim txtEmail As RadTextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Email), RadTextBox)
            blnUpdateEmail = (Not txtEmail Is Nothing)

            If blnUpdateEmail Then
                If Not IsValidUserAttribute(Constants.User_Email, plhProfile) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Email, plhProfile)
                Else
                    RemoveErrorIndicator(Constants.User_Email, plhProfile, True)
                End If
            End If

            Dim txtPassword As RadTextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Password1), RadTextBox)
            Dim txtPassword2 As RadTextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Password2), RadTextBox)
            blnUpdatePassword = (Not txtPassword Is Nothing AndAlso Not txtPassword2 Is Nothing)

            If blnUpdatePassword Then
                If txtPassword.Text = "" AndAlso txtPassword2.Text = "" Then
                    blnUpdatePassword = False
                End If
            End If

            If blnUpdatePassword Then
                If Not IsValidUserAttribute(Constants.User_Password1, plhProfile) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Password1, plhProfile)
                Else
                    RemoveErrorIndicator(Constants.User_Password1, plhProfile, True)
                End If
                If Not IsValidUserAttribute(Constants.User_Password2, plhProfile) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Password2, plhProfile)
                Else
                    RemoveErrorIndicator(Constants.User_Password2, plhProfile, True)
                End If
            End If

            Dim txtFirstName As RadTextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Firstname), RadTextBox)
            blnUpdateFirstname = (Not txtFirstName Is Nothing)

            If blnUpdateFirstname Then
                If Not IsValidUserAttribute(Constants.User_Firstname, plhProfile) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Firstname, plhProfile)
                Else
                    RemoveErrorIndicator(Constants.User_Firstname, plhProfile, True)
                End If
            End If

            Dim txtLastName As RadTextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Lastname), RadTextBox)
            blnUpdateLastname = (Not txtLastName Is Nothing)

            If blnUpdateLastname Then
                If Not IsValidUserAttribute(Constants.User_Lastname, plhProfile) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Lastname, plhProfile)
                Else
                    RemoveErrorIndicator(Constants.User_Lastname, plhProfile, True)
                End If
            End If

            Dim txtDisplayName As RadTextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Displayname), RadTextBox)
            blnUpdateDisplayname = (Not txtDisplayName Is Nothing)

            If blnUpdateDisplayname Then
                If Not IsValidUserAttribute(Constants.User_Displayname, plhProfile) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Displayname, plhProfile)
                Else
                    RemoveErrorIndicator(Constants.User_Displayname, plhProfile, True)
                End If
            End If

            For Each itemProp As String In GetPropertiesFromTempate(Template_UserProfile(CurrentLocale))
                Try
                    Dim prop As ProfilePropertyDefinition = ProfileController.GetPropertyDefinitionByName(PortalId, itemProp.Substring(2)) 'itemprop comes in the form U:Propertyname or P:Propertyname
                    If Not prop Is Nothing Then
                        If Not IsValidProperty(UserInfo, prop, plhProfile) Then
                            strMessage += "Error"
                            AddErrorIndicator(prop.PropertyDefinitionId.ToString, plhProfile)
                        Else
                            RemoveErrorIndicator(prop.PropertyDefinitionId.ToString, plhProfile, prop.Required)
                        End If
                    End If
                Catch
                End Try
            Next

            If strMessage.Length > 0 Then
                Me.pnlError.Visible = True
                Me.lblError.Text = "<ul><li>" & Localization.GetString("FillInAll", Me.SharedResourcefile) & "</li></ul>"
                Exit Sub
            End If

            Dim oUser As UserInfo = UserController.GetCurrentUserInfo
            Dim oldAccount As UserInfo = UserController.GetCurrentUserInfo

            If blnUpdateEmail Then
                oUser.Email = txtEmail.Text
                If oUser.Email <> oldAccount.Email Then
                    strUpdated += Localization.GetString("Email", SharedResourcefile) & ", "
                End If
            End If

            'try updating password
            If blnUpdatePassword Then
                If txtPassword.Text = txtPassword2.Text Then
                    If UserController.ValidatePassword(txtPassword.Text) Then
                        UserController.ChangePassword(oUser, "", txtPassword.Text)
                        strUpdated += Localization.GetString("Password", SharedResourcefile) & ", "
                    Else
                        Me.pnlError.Visible = True
                        Me.lblError.Text = "<ul><li>" & Localization.GetString("InvalidPassword.Text", SharedResourcefile) & "</li></ul>"
                        Exit Sub
                    End If
                Else
                    Me.pnlError.Visible = True
                    Me.lblError.Text = "<ul><li>" & Localization.GetString("PasswordsDontMatch.Text", SharedResourcefile) & "</li></ul>"
                    Exit Sub
                End If
            End If

            'loop trough dynamic profile attributes and set those
            For Each itemProp As String In GetPropertiesFromTempate(Template_UserProfile(CurrentLocale))
                Try
                    Dim prop As ProfilePropertyDefinition = ProfileController.GetPropertyDefinitionByName(PortalId, itemProp.Substring(2))
                    If Not prop Is Nothing Then

                        Dim ctl As Control = GetPropertyControl(prop, plhProfile)
                        If Not ctl Is Nothing Then
                            If TypeOf (ctl) Is Telerik.Web.UI.RadComboBox Then

                                Dim value As String = CType(ctl, Telerik.Web.UI.RadComboBox).SelectedValue.Trim

                                If oldAccount.Profile.GetPropertyValue(prop.PropertyName) <> value Then
                                    Dim strProperty As String = prop.PropertyName
                                    If Localization.GetString("ProfileProperties_" & prop.PropertyName, ProfileResourcefile) <> "" Then
                                        strProperty = Localization.GetString("ProfileProperties_" & prop.PropertyName & ".Text", ProfileResourcefile)
                                    End If
                                    strUpdated += strProperty & ", "
                                End If

                                oUser.Profile.SetProfileProperty(prop.PropertyName, value)

                            ElseIf TypeOf (ctl) Is Telerik.Web.UI.RadDateTimePicker Then

                                Dim value As String = CType(ctl, Telerik.Web.UI.RadDateTimePicker).DbSelectedDate.ToString

                                If oldAccount.Profile.GetPropertyValue(prop.PropertyName) <> value Then
                                    Dim strProperty As String = prop.PropertyName
                                    If Localization.GetString("ProfileProperties_" & prop.PropertyName, ProfileResourcefile) <> "" Then
                                        strProperty = Localization.GetString("ProfileProperties_" & prop.PropertyName & ".Text", ProfileResourcefile)
                                    End If
                                    strUpdated += strProperty & ", "
                                End If

                                oUser.Profile.SetProfileProperty(prop.PropertyName, value)

                            ElseIf TypeOf (ctl) Is Telerik.Web.UI.RadTimePicker Then

                                Dim value As String = CType(ctl, Telerik.Web.UI.RadTimePicker).DbSelectedDate.ToString.Trim

                                If oldAccount.Profile.GetPropertyValue(prop.PropertyName) <> value Then
                                    Dim strProperty As String = prop.PropertyName
                                    If Localization.GetString("ProfileProperties_" & prop.PropertyName, ProfileResourcefile) <> "" Then
                                        strProperty = Localization.GetString("ProfileProperties_" & prop.PropertyName & ".Text", ProfileResourcefile)
                                    End If
                                    strUpdated += strProperty & ", "
                                End If

                                oUser.Profile.SetProfileProperty(prop.PropertyName, value)

                            ElseIf TypeOf (ctl) Is Telerik.Web.UI.RadDatePicker Then

                                Dim value As String = CType(ctl, Telerik.Web.UI.RadDatePicker).DateInput.DbSelectedDate.ToString.Trim

                                If oldAccount.Profile.GetPropertyValue(prop.PropertyName) <> value Then
                                    Dim strProperty As String = prop.PropertyName
                                    If Localization.GetString("ProfileProperties_" & prop.PropertyName, ProfileResourcefile) <> "" Then
                                        strProperty = Localization.GetString("ProfileProperties_" & prop.PropertyName & ".Text", ProfileResourcefile)
                                    End If
                                    strUpdated += strProperty & ", "
                                End If

                                oUser.Profile.SetProfileProperty(prop.PropertyName, value)

                            ElseIf TypeOf (ctl) Is CheckBox Then

                                Dim value As String = CType(ctl, CheckBox).Checked.ToString

                                If oldAccount.Profile.GetPropertyValue(prop.PropertyName) <> value Then
                                    Dim strProperty As String = prop.PropertyName
                                    If Localization.GetString("ProfileProperties_" & prop.PropertyName, ProfileResourcefile) <> "" Then
                                        strProperty = Localization.GetString("ProfileProperties_" & prop.PropertyName & ".Text", ProfileResourcefile)
                                    End If
                                    strUpdated += strProperty & ", "
                                End If

                                oUser.Profile.SetProfileProperty(prop.PropertyName, value)

                            ElseIf TypeOf (ctl) Is Telerik.Web.UI.RadTextBox Then

                                Dim value As String = CType(ctl, Telerik.Web.UI.RadTextBox).Text.Trim

                                Dim oldValue As String = oldAccount.Profile.GetPropertyValue(prop.PropertyName)
                                If oldValue <> value Then
                                    Dim strProperty As String = prop.PropertyName
                                    If Localization.GetString("ProfileProperties_" & prop.PropertyName, ProfileResourcefile) <> "" Then
                                        strProperty = Localization.GetString("ProfileProperties_" & prop.PropertyName & ".Text", ProfileResourcefile)
                                    End If
                                    strUpdated += strProperty & ", "
                                End If

                                oUser.Profile.SetProfileProperty(prop.PropertyName, value)



                            ElseIf TypeOf (ctl) Is Telerik.Web.UI.RadNumericTextBox Then

                                Dim value As String = CType(ctl, Telerik.Web.UI.RadNumericTextBox).Value.ToString

                                If oldAccount.Profile.GetPropertyValue(prop.PropertyName) <> value Then
                                    Dim strProperty As String = prop.PropertyName
                                    If Localization.GetString("ProfileProperties_" & prop.PropertyName, ProfileResourcefile) <> "" Then
                                        strProperty = Localization.GetString("ProfileProperties_" & prop.PropertyName & ".Text", ProfileResourcefile)
                                    End If
                                    strUpdated += strProperty & ", "
                                End If

                                oUser.Profile.SetProfileProperty(prop.PropertyName, value)

                            ElseIf TypeOf (ctl) Is Telerik.Web.UI.RadAsyncUpload Then
                                Dim objFile As UploadedFile = CType(ctl, Telerik.Web.UI.RadUpload).UploadedFiles(0)
                                If Not objFile Is Nothing Then
                                    Dim strFile As String = objFile.GetName
                                    Dim path As String = "Profile/" & prop.PropertyName & "/" & oUser.Username & "/" & strFile

                                    If oldAccount.Profile.GetPropertyValue(prop.PropertyName) <> path Then
                                        Dim strProperty As String = prop.PropertyName
                                        If Localization.GetString("ProfileProperties_" & prop.PropertyName, ProfileResourcefile) <> "" Then
                                            strProperty = Localization.GetString("ProfileProperties_" & prop.PropertyName & ".Text", ProfileResourcefile)
                                        End If
                                        strUpdated += strProperty & ", "
                                    End If

                                    oUser.Profile.SetProfileProperty(prop.PropertyName, path)

                                End If
                            End If
                        End If

                    End If
                Catch
                End Try
            Next

            'make sure first and lastname are in sync with user and profile object
            If blnUpdateFirstname = True Then
                If oldAccount.FirstName <> txtFirstName.Text Then
                    strUpdated += Localization.GetString("Firstname", SharedResourcefile) & ", "
                End If
                oUser.Profile.FirstName = txtFirstName.Text
                oUser.FirstName = txtFirstName.Text
            Else
                If oUser.Profile.FirstName <> "" Then
                    oUser.FirstName = oUser.Profile.FirstName
                End If
            End If

            If blnUpdateLastname = True Then
                If oldAccount.LastName <> txtLastName.Text Then
                    strUpdated += Localization.GetString("Lastname", SharedResourcefile) & ", "
                End If
                oUser.Profile.LastName = txtLastName.Text
                oUser.LastName = txtLastName.Text
            Else
                If oUser.Profile.LastName <> "" Then
                    oUser.LastName = oUser.Profile.LastName
                End If
            End If

            If blnUpdateDisplayname Then
                If oldAccount.DisplayName <> txtDisplayName.Text Then
                    strUpdated += Localization.GetString("Displayname", SharedResourcefile) & ", "
                End If
                oUser.DisplayName = txtDisplayName.Text
            Else
                Select Case DisplaynameMode
                    Case DisplaynameUpdateMode.Email
                        If blnUpdateEmail Then
                            oUser.DisplayName = txtEmail.Text.Trim
                        End If
                    Case DisplaynameUpdateMode.FirstLetterLastname
                        If blnUpdateLastname AndAlso blnUpdateFirstname Then
                            oUser.DisplayName = oUser.FirstName.Trim.Substring(0, 1) & ". " & oUser.LastName
                        End If
                    Case DisplaynameUpdateMode.FirstnameLastname
                        If blnUpdateLastname AndAlso blnUpdateFirstname Then
                            oUser.DisplayName = oUser.FirstName & " " & oUser.LastName
                        End If
                    Case DisplaynameUpdateMode.Lastname
                        If blnUpdateLastname Then
                            oUser.DisplayName = oUser.LastName
                        End If
                End Select
            End If

            'update profile
            UserController.UpdateUser(PortalId, oUser)

            'add to role
            If AddToRoleOnSubmit <> Null.NullInteger Then
                Try
                    Dim rc As New Security.Roles.RoleController
                    rc.AddUserRole(PortalId, oUser.UserID, AddToRoleOnSubmit, Null.NullDate)
                Catch
                End Try
            End If

            'remove from role
            If RemoveFromRoleOnSubmit <> Null.NullInteger Then
                Try
                    Dim rc As New Security.Roles.RoleController
                    rc.DeleteUserRole(PortalId, oUser.UserID, RemoveFromRoleOnSubmit)
                Catch
                End Try
            End If

            'notify admin   
            If NotifyAddress <> "" AndAlso strUpdated.Length > 0 Then

                Dim strBody As String = Template_Email_ProfileUpdate_Admin(CurrentLocale)

                strBody = strBody.Replace("[PORTALURL]", PortalSettings.PortalAlias.HTTPAlias)
                strBody = strBody.Replace("[PORTALNAME]", PortalSettings.PortalName)
                strBody = strBody.Replace("[USERID]", oUser.UserID)
                strBody = strBody.Replace("[DISPLAYNAME]", oUser.DisplayName)
                strBody = strBody.Replace("[PASSWORD]", MembershipProvider.Instance().GetPassword(oUser, ""))
                strBody = strBody.Replace("[USERNAME]", oUser.Username)
                strBody = strBody.Replace("[FIRSTNAME]", oUser.FirstName)
                strBody = strBody.Replace("[LASTNAME]", oUser.LastName)
                strBody = strBody.Replace("[UPDATED]", strUpdated.Substring(0, strUpdated.LastIndexOf(",")).Replace(":", ""))
                strBody = strBody.Replace("[USERURL]", NavigateURL(UsermanagementTab, "", "uid=" & oUser.UserID.ToString))

                Try
                    Services.Mail.Mail.SendMail(PortalSettings.Email, NotifyAddress, "", String.Format(Localization.GetString("NotifySubject_ProfileUpdate", SharedResourcefile), PortalSettings.PortalName), strBody, "", "HTML", "", "", "", "")
                Catch
                End Try

            End If

            If NotifyUser AndAlso strUpdated.Length > 0 Then

                Dim strBody As String = Template_Email_ProfileUpdate_User(oUser.Profile.PreferredLocale)

                strBody = strBody.Replace("[PORTALURL]", PortalSettings.PortalAlias.HTTPAlias)
                strBody = strBody.Replace("[PORTALNAME]", PortalSettings.PortalName)
                strBody = strBody.Replace("[USERID]", oUser.UserID)
                strBody = strBody.Replace("[DISPLAYNAME]", oUser.DisplayName)
                strBody = strBody.Replace("[PASSWORD]", MembershipProvider.Instance().GetPassword(oUser, ""))
                strBody = strBody.Replace("[USERNAME]", oUser.Username)
                strBody = strBody.Replace("[FIRSTNAME]", oUser.FirstName)
                strBody = strBody.Replace("[LASTNAME]", oUser.LastName)
                strBody = strBody.Replace("[UPDATED]", strUpdated.Substring(0, strUpdated.LastIndexOf(",")).Replace(":", ""))
                strBody = strBody.Replace("[USERURL]", NavigateURL(TabId))

                Try
                    Services.Mail.Mail.SendMail(PortalSettings.Email, oUser.Email, "", String.Format(Localization.GetString("NotifySubject_ProfileUpdate", SharedResourcefile), PortalSettings.PortalName), strBody, "", "HTML", "", "", "", "")
                Catch
                End Try

            End If

            lblSucess.Text = "<ul><li>" & Localization.GetString("ProfileUpdateSuccess.Text", SharedResourcefile) & "</li></ul>"
            pnlSuccess.Visible = True

            If Not Request.QueryString("ReturnURL") Is Nothing Then
                Response.Redirect(Request.QueryString("ReturnURL"), True)
            End If

            If RedirectAfterSubmit <> "" Then
                Response.Redirect(RedirectAfterSubmit, True)
            End If

        End Sub

        Private Sub DeleteAccount()

            Dim oUser As UserInfo = UserController.GetCurrentUserInfo

            If UserController.DeleteUser(oUser, False, False) Then
                lblSucess.Text = "<ul><li>" & Localization.GetString("AccountDeleted.Text", SharedResourcefile) & "</li></ul>"
                pnlSuccess.Visible = True
            Else
                lblError.Text = "<ul><li>" & Localization.GetString("AccountNotDeleted.Text", SharedResourcefile) & "</li></ul>"
                pnlError.Visible = True
            End If

        End Sub

        Public Function InvalidEmailString() As String
            Return Localization.GetString("InvalidPassword.Text", SharedResourcefile)
        End Function

        Public Function ValidPasswordString() As String
            Return Localization.GetString("ValidPassword.Text", SharedResourcefile)
        End Function

        Public Function InvalidPasswordString() As String
            Return Localization.GetString("InvalidPassword.Text", SharedResourcefile)
        End Function

        Public Function PasswordsDontMatchString() As String
            Return Localization.GetString("PasswordsDontMatch.Text", SharedResourcefile)
        End Function

        Public Function MinPasswordLength() As String
            Return "7"
        End Function

        Public Function ErrorImageUrl() As String
            Return (Me.ModuleDirectory & "/images/error.png").Replace("~", "")
        End Function

        Public Function AcceptImageUrl() As String
            Return (Me.ModuleDirectory & "/images/accept.png").Replace("~", "")
        End Function

        Public Function Password1Id() As String
            Dim txtPassword As RadTextBox = CType(FindControlRecursive(plhProfile, plhProfile.ID & "_" & Constants.ControlId_Password1), RadTextBox)
            If Not txtPassword Is Nothing Then
                Return txtPassword.ClientID
            End If
            Return ""
        End Function

#End Region

    End Class

End Namespace
